#!/usr/bin/env bash
# ******************************************************
# Filename     : backfile.sh
# Last modified: 2017-07-03 11:18
# Version      : 
# Author       : jack.zang
# Email        : jack.zang@aishangwei.net
# Description  : 凡是 ### 开头的部分，都需要你根据实际情况配置
# ******************************************************

ip=`awk '/IPADDR/' /etc/sysconfig/network-scripts/ifcfg-eth0 |awk -F "=" '{print $2}'`

### 配置备份选项
sourdir=/data/www/sgj.game.rshui.cn
backdir=/data/backup/www
backprefix=sgi.game.rshui.cn

### 配置发送邮件人
maillist="zangxuefeng@rshui.cn"

dateb=`date +%Y%m%d`
# 打包备份
file_back() {
     [ ! -d ${backdir} ] && mkdir ${backdir} -p
     
     # 备份文件
     if [ -d ${sourdir} ];then
         cd ${sourdir}
         # 如果备份指定文件，更改 ./*
         tar zcf ${backdir}/${backprefix}_${ip}_${dateb}.tar.gz ./*
         echo "" > ${backdir}/file_back_${dateb}.log
     else
         echo "failed--`date +%F-%R` backdir ${sourdir} is not exist!" >> ${backdir}/file_back_${dateb}.log
     fi
     
	 # del old backup
        findf=$(find ${backdir} -name "*.gz" -mtime +30 -o -name "*.log" -mtime +30) 
		if [ -n "${findf}" ];then
		    rm -f $findf
			echo  "succeed--`date +%F-%R` delete backup $backdir/$findf succeed." >> ${backdir}/file_back_${dateb}.log
        fi
	 
     # 检测是否备份成功
     if [ -e "$backdir/${backprefix}_${ip}_${dateb}.tar.gz" ];then
        echo "succeed--`date +%F-%R` backup ${backprefix}_${ip}_${dateb}.tar.gz succeed." >> ${backdir}/file_back_${dateb}.log
     else
        echo "failed--`date +%F-%R` backup ${backprefix}_${ip}_${dateb}.tar.gz failed!" >> ${backdir}/file_back_${dateb}.log
     fi
}

# 发送邮件
mail_to() { 
     mailx -s "系统备份日志" -r ${ip}@aishangwei.net  ${maillist} < ${backdir}/file_back_${dateb}.log
}

# ftp上传
ftp_upload() {
     dateb=`date +%Y%m%d`
	 ### 上传文件的目录
     uploadpath[1]="${backdir}"
     ftpip="103.244.234.150:21"
     ftpuser="chushang"
     ftppasswd="bn<67^adt6"

type lftp 1>/dev/null 2>/dev/null || yum -y install lftp
     for p in ${uploadpath[@]}
     do
	     ### 过滤要上传的文件 
         uploadfile="`ls $p |grep $dateb`"

         for f in $uploadfile
         do
cat >/tmp/ftpcmd.txt<<EOF
open $ftpip
user "${ftpuser}" "${ftppasswd}"
mput $p/$f
bye
EOF
         lftp -f /tmp/ftpcmd.txt
         done
     done
rm -f /tmp/ftpcmd.txt
}

echo "" >${backdir}/file_back_${dateb}.log
file_back
#mail_to
ftp_upload